package com.sy.simpleegg.ui.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSnapHelper
import com.bumptech.glide.Glide
import com.sy.simpleegg.BuildConfig
import com.sy.simpleegg.R
import com.sy.simpleegg.adapter.GoodAdapter
import com.sy.simpleegg.adapter.GoodForeignAdapter
import com.sy.simpleegg.adapter.HomeBtnAdapter
import com.sy.simpleegg.adapter.RegCodeAdapter
import com.sy.simpleegg.app.App
import com.sy.simpleegg.base.BaseMvpFragment
import com.sy.simpleegg.bean.CashGoodBean
import com.sy.simpleegg.bean.CheckSaveCoinsResultBean
import com.sy.simpleegg.bean.CouponInfoBean
import com.sy.simpleegg.bean.GetWithdrawalCodeResult
import com.sy.simpleegg.bean.GoodBean
import com.sy.simpleegg.bean.GoodListBean
import com.sy.simpleegg.bean.HomeBtnBean
import com.sy.simpleegg.bean.HomeBtnItemBean
import com.sy.simpleegg.bean.PayIconBean
import com.sy.simpleegg.bean.PayTypeData
import com.sy.simpleegg.bean.PayTypeDataYch
import com.sy.simpleegg.bean.RepWriteOffDataBean
import com.sy.simpleegg.bean.ReqBackscanPayBean
import com.sy.simpleegg.bean.ReqPayCodeBean
import com.sy.simpleegg.bean.ReqStartResultBean
import com.sy.simpleegg.bean.SaveCoinLoginBean
import com.sy.simpleegg.bean.WithdrawalGoodBean
import com.sy.simpleegg.config.Config
import com.sy.simpleegg.constant.Constant
import com.sy.simpleegg.constant.Constant.KEYBOARD_CLICK_COUNT
import com.sy.simpleegg.constant.HomeButtonType
import com.sy.simpleegg.constant.PackageType
import com.sy.simpleegg.constant.ProductType
import com.sy.simpleegg.databinding.FragmentHomeBinding
import com.sy.simpleegg.event.BanknoteEvent
import com.sy.simpleegg.event.CouponVerificationEvent
import com.sy.simpleegg.event.ScanEvent
import com.sy.simpleegg.event.DevRegisterEvent
import com.sy.simpleegg.event.DispenserOrderEvent
import com.sy.simpleegg.event.GetDeviceIdleEvent
import com.sy.simpleegg.event.GetDeviceIdleRespEvent
import com.sy.simpleegg.event.GetLoginCodeEvent
import com.sy.simpleegg.event.GetPayCodeEvent
import com.sy.simpleegg.event.GetWithdrawalCodeEvent
import com.sy.simpleegg.event.OutCoinsEvent
import com.sy.simpleegg.event.PlaceCashOrderEvent
import com.sy.simpleegg.event.PlaceLocalWithdrawalOrderEvent
import com.sy.simpleegg.event.PlaceLocalWithdrawalOrderRespEvent
import com.sy.simpleegg.event.PlaceOrderEvent
import com.sy.simpleegg.event.PostBackscanPayEvent
import com.sy.simpleegg.event.PostCashEvent
import com.sy.simpleegg.event.PostResultEvent
import com.sy.simpleegg.event.PostWriteOffDataEvent
import com.sy.simpleegg.event.QueryLgLoginCancelEvent
import com.sy.simpleegg.event.QueryPlaceOrderCancelEvent
import com.sy.simpleegg.event.ReceiveOrderEvent
import com.sy.simpleegg.event.ReceiveOrderKkbHttpEvent
import com.sy.simpleegg.event.ReceiveOrderYchHttpEvent
import com.sy.simpleegg.event.ReceiveWithdrawalOrderEvent
import com.sy.simpleegg.event.ReceiveWriteOffOrderEvent
import com.sy.simpleegg.event.ReceivedScanDataEvent
import com.sy.simpleegg.event.RefreshCashDataEvent
import com.sy.simpleegg.event.RefreshCoinsEvent
import com.sy.simpleegg.event.RefreshDeviceNumberEvent
import com.sy.simpleegg.event.RefreshGoodsEvent
import com.sy.simpleegg.event.RefreshSignalEvent
import com.sy.simpleegg.event.RepSaveCoinDataEvent
import com.sy.simpleegg.event.SaveCoinEvent
import com.sy.simpleegg.event.ShowCodeEvent
import com.sy.simpleegg.event.ShowPayQrCodeEvent
import com.sy.simpleegg.event.SwitchFragmentEvent
import com.sy.simpleegg.event.UserLoginEvent
import com.sy.simpleegg.event.UserLoginKkbEvent
import com.sy.simpleegg.event.UserLoginYchEvent
import com.sy.simpleegg.event.WirteOffResultEvent
import com.sy.simpleegg.ext.getDeviceStatus
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.ext.onClick
import com.sy.simpleegg.ext.showToastMsg
import com.sy.simpleegg.mvp.contract.HomeContract
import com.sy.simpleegg.mvp.presenter.HomePresenter
import com.sy.simpleegg.platform.BackstagePlatform
import com.sy.simpleegg.platform.kkb.bean.KkbBuyPackageBean
import com.sy.simpleegg.platform.whmhex.bean.WriteOffRespWhmMqttHexBean
import com.sy.simpleegg.room.entity.OrderEntity
import com.sy.simpleegg.serialport.backscan.ScanType
import com.sy.simpleegg.ui.banner.adapter.MediaVideoBannerAdapter
import com.sy.simpleegg.ui.banner.bean.ResourceBean
import com.sy.simpleegg.ui.banner.manager.BannerVideoManager
import com.sy.simpleegg.ui.dialog.CashPayDialog
import com.sy.simpleegg.ui.dialog.CoinsInfoDialog
import com.sy.simpleegg.ui.dialog.CouponDialog
import com.sy.simpleegg.ui.dialog.InfoDialog
import com.sy.simpleegg.ui.dialog.KeyboardDialog
import com.sy.simpleegg.ui.dialog.KkbPayDialog
import com.sy.simpleegg.ui.dialog.LocalWithdrawalDialog
import com.sy.simpleegg.ui.dialog.MultCouponDialog
import com.sy.simpleegg.ui.dialog.PayTypeDialog
import com.sy.simpleegg.ui.dialog.PaymentDialog
import com.sy.simpleegg.ui.dialog.SaveCoinDialog
import com.sy.simpleegg.ui.dialog.WithdrawalDialog
import com.sy.simpleegg.ui.dialog.YchPayDialog
import com.sy.simpleegg.ui.fragment.config.FragmentEnum
import com.sy.simpleegg.util.BigDecimalUtil
import com.sy.simpleegg.util.FileUtil
import com.sy.simpleegg.util.GsonUtil
import com.sy.simpleegg.util.Preference
import com.sy.simpleegg.util.SoftInputUtil
import com.sy.mqhexsdk.bean.rec.RecUserInfo
import com.youth.banner.config.IndicatorConfig
import com.youth.banner.indicator.CircleIndicator
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class HomeFragment :
    BaseMvpFragment<HomeContract.View, HomeContract.Presenter, FragmentHomeBinding>(),
    HomeContract.View {

    private var mAdapter: MediaVideoBannerAdapter? = null
    private var mBannerVideoManager: BannerVideoManager? = null

    //    private var tabAdapter: TabAdapter? = null
//    private var verticalGoodAdater: VerticalGoodsAdapter? = null
//
//    private var paymentOutInfoDialog: PaymentOutInfoDialog? = null
//    private var cartListDialog: ShoppingCartDialog? = null
//    private var detailDialog: GoodDetailDialog? = null
//
    private var lastClickTime: Long = 0L
    private var curClickTime: Long = 0L
    private var clickCount: Int = 1
//
//    private var currentState = HandleState.VERIFY
//    private var currentOrder: OrderEntity? = null

    private lateinit var homeBtnNames: Array<HomeBtnItemBean>
    private var homeBtnAdapter: HomeBtnAdapter? = null

    private var normalPackageAdapter: GoodAdapter? = null
    private var rechargePackageAdapter: GoodAdapter? = null
    private var normalPackageForeignAdapter: GoodForeignAdapter? = null
    private var regCodeAdapter: RegCodeAdapter? = null

    private var couponDialog: CouponDialog? = null
    private var payTypeDialog: PayTypeDialog? = null
    private var paymentDialog: PaymentDialog? = null
    private var coinsInfoDialog: CoinsInfoDialog? = null
    private var cashPayDialog: CashPayDialog? = null
    private var withdrawalDialog: WithdrawalDialog? = null
    private var localWithdrawalDialog: LocalWithdrawalDialog? = null
    private var saveCoinDialog: SaveCoinDialog? = null
    private var infoDialog: InfoDialog? = null
    private var keyboardDialog: KeyboardDialog? = null
    private var ychPayDialog: YchPayDialog? = null
    private var kkbPayDialog: KkbPayDialog? = null
    private var multCouponDialog: MultCouponDialog? = null

    private var scanType = ScanType.UNDEFINE
    private var scanK = ""

    private var userInfo: RecUserInfo? = null

    /**
     * 显示指示器
     */
    private var canShowIndicater: Boolean by Preference(Constant.SETTING_SHOW_INDICATOR, false)

    /**
     * 滑动banner
     */
    private var canSrollBanner: Boolean by Preference(Constant.SETTING_SCORLL_BANNER, false)

    /**
     * 拖动视频进度，音量，亮度等
     */
    private var canTouchWidget: Boolean by Preference(Constant.SETTING_TOUCH_WIDGET, false)

    /**
     * 图片显示时间
     */
    private var imageShowTime: Long by Preference(Constant.SETTING_IMAGE_SHOW_TIME, 5000)

    /**
     * 视频前置时间
     */
    private var videoLoadTime: Long by Preference(Constant.SETTING_VIDEO_LOAD_WAIT_TIME, 500)

    /**
     * 主推广告(显示小广告？)
     */
    private var smallAd: Boolean by Preference(Constant.SETTING_PUSH_AD, true)

    /**
     * 允许商品列表滚动
     */
    private var goodSmooth: Boolean by Preference(Constant.SETTING_CHANNEL_ROTATE, true)

    /**
     * 货道号显示
     */
    private var channelShow: Boolean by Preference(Constant.SETTING_CHANNEL_SHOW, true)

    /**
     * logo显示
     */
    private var logoShow: Boolean by Preference(Constant.SETTING_LOGO_SHOW, true)

    /**
     * 显示购物车
     */
    private var showShopCart: Boolean by Preference(Constant.SETTING_SHOPPING_CART, true)

    /**
     * 支付倒计时
     */
    private var payTimeout: Int by Preference(Constant.SETTING_PAY_TIMEOUT, Config.PAY_TIMEOUT)

    /**
     * 支付结果显示倒计时
     */
    private var payResultTimeout: Int by Preference(
        Constant.SETTING_PAY_RESULT_TIMEOUT,
        Config.PAY_RESULT_TIMEOUT
    )

    /**
     * 取货倒计时
     */
    private var takeTimeout: Int by Preference(Constant.SETTING_TAKE_TIMEOUT, Config.TAKE_TIMEOUT)

    /**
     * 出货超时时间
     */
    private var defaultTimeout: Int by Preference(
        Constant.SETTING_DEFAULT_TIMEOUT,
        Config.DEF_OUTTING_TIMEOUT
    )

    /**
     * 设备编号
     */
    private var devNumber: String by Preference(Constant.SETTING_DEVICE_NUMBER, "")


    /**
     * 接入第三方平台
     */
    private var platform: BackstagePlatform by Preference(Constant.SETTING_OTHER_PLATFORM, BackstagePlatform.WHM_MQTT_HEX)

    /**
     * 默认mq通讯
     */
    private var defmqOpen: Boolean by Preference(Constant.SETTING_DEFMQ_OPEN, BuildConfig.DEF_MQ_OPEN)
    /**
     * lyysdk通讯
     */
    private var lyysdkOpen: Boolean by Preference(Constant.SETTING_LYYSDK_OPEN, BuildConfig.LYYSDK_OPEN)
    /**
     * lyybox通讯
     */
    private var lyyboxOpen: Boolean by Preference(Constant.SETTING_LYYBOX_OPEN, BuildConfig.LYYBOX_OPEN)
    /**
     * lyybox二维码
     */
    private var lyyboxQrCode: String by Preference(Constant.SETTING_LYYBOX_QR_CODE, "")
    /**
     * 自动补币（无限币）
     */
    private var autoCoins: Boolean by Preference(Constant.SETTING_AUTO_COINS, true)
    /**
     * 客服电话
     */
    private var contact: String by Preference(Constant.SETTING_CONTACT, "")
    /**
     * 支付方式
     */
    private var payTypeStr: String by Preference(Constant.SETTING_PAY_TYPE, "")
    /**
     * 现金投币按钮显示状态
     */
    private var cashShow: Boolean by Preference(Constant.SETTING_CASH_SHOW, true)
    /**
     * 美团核销按钮显示状态
     */
    private var meituanShow: Boolean by Preference(Constant.SETTING_MEITUAN_SHOW, true)
    /**
     * 抖音核销按钮显示状态
     */
    private var tiktokShow: Boolean by Preference(Constant.SETTING_TIKTOK_SHOW, true)
    /**
     * 会员存币按钮显示状态
     */
    private var saveShow: Boolean by Preference(Constant.SETTING_SAVE_SHOW, true)
    /**
     * 核销按钮显示状态
     */
    private var writeOffShow: Boolean by Preference(Constant.SETTING_WRITE_OFF_SHOW, true)
    /**
     * 提币按钮显示状态
     */
    private var withdrawalShow: Boolean by Preference(Constant.SETTING_WITHDRAWAL_SHOW, true)
    /**
     * 国家地区
     */
    private var country: Int by Preference(Constant.SETTING_COUNTRY, Config.DEFAULT_COUNTRY_CODE)
    /**
     * 首页说明内容
     */
    private var instructions: String by Preference(Constant.SETTING_HOME_INSTRUCTIONS, "")
    /**
     * 设备码
     */
    private var loginCode: String by Preference(Constant.SETTING_LOGIN_CODE, "")
    /**
     * 提币二维码
     */
    private var withdrawalCode: String by Preference(Constant.SETTING_WITHDRAWAL_CODE, "")
    /**
     * 设备消费二维码
     */
    private var devConsumeCode: String by Preference(Constant.SETTING_CONSUME_CODE, "")

    companion object {
        fun getInstance(): HomeFragment = HomeFragment()
    }

    override fun createPresenter(): HomeContract.Presenter = HomePresenter(lifecycleScope)

    override fun attachLayoutRes(): Int = R.layout.fragment_home

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        openEventBus = true
        isCountDownBackHome = true
        homeBtnNames = arrayOf(
            HomeBtnItemBean(getString(when (Config.PRODUCT_TYPE){
                ProductType.CURRENCY -> R.string.cash_pay
                ProductType.BEAD -> R.string.cash_pay_bead
            }), HomeButtonType.CASH, cashShow),
            HomeBtnItemBean(getString(when (Config.PRODUCT_TYPE){
                ProductType.CURRENCY -> R.string.member_withdrawal
                ProductType.BEAD -> R.string.member_withdrawal_bead
            }), HomeButtonType.WITHDRAWAL, withdrawalShow),
//            HomeBtnItemBean(getString(R.string.mobile_pay), HomeButtonType.MOBILE_PAY),
            HomeBtnItemBean(getString(R.string.coupon), HomeButtonType.COUPON, writeOffShow),
            HomeBtnItemBean(
                getString(R.string.meituan_coupon),
                HomeButtonType.MEITUAN_COUPON,
                meituanShow
            ),
            HomeBtnItemBean(
                getString(R.string.titok_coupon),
                HomeButtonType.TIKTOK_COUPON,
                tiktokShow
            ),
            HomeBtnItemBean(
                getString(when (Config.PRODUCT_TYPE){
                    ProductType.CURRENCY -> R.string.member_save_coins
                    ProductType.BEAD -> R.string.member_save_bead
                }),
                HomeButtonType.SAVE,
                saveShow
            ),
        )
    }

    override fun initView(view: View) {
        super.initView(view)
        mPresenter?.initHandleJob()

        binding.etUsbScan.showSoftInputOnFocus = false
        binding.etUsbScan.requestFocus()

        isShowLogo(logoShow)

        isShowSmallAd(smallAd)

        binding.tvDeviceNumber.text = devNumber

        binding.llContact.onClick {
            showInfo(getString(R.string.contact_phone), contact)
        }

        binding.btnBackstage.setOnClickListener {
            openKeyboard()
        }

        binding.rlRechargeBtn.onClick {
            mPresenter?.getWithdrawalCode(platform)
        }

        //加载余币数据
        loadCoins(autoCoins)

        loadOptionItem()
    }

    /**
     * 加载设备余币
     */
    private fun loadCoins(isAutoCoins: Boolean){
        if (isAutoCoins){
            refreshCoins("∞")
        }else{
            mPresenter?.loadCoins()
        }
    }

    /**
     * 刷新设备余币
     * @param coins 币数
     */
    private fun refreshCoins(coins: String){
        binding.tvRemainCoin.text = coins
    }

    private fun postCashData(repData: Any){
        EventBus.getDefault().post(PostCashEvent(repData))
    }

    private fun openKeyboard() {
        lastClickTime = curClickTime
        curClickTime = System.currentTimeMillis()
        if (curClickTime - lastClickTime < 500) {
            clickCount++
            if (clickCount == KEYBOARD_CLICK_COUNT) {
                clickCount = 1
                showKeyboardDialog()
            }else if(clickCount > KEYBOARD_CLICK_COUNT){
                clickCount = 1
            }
        } else {
            clickCount = 1
        }
    }

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
    ) = FragmentHomeBinding.inflate(inflater, container, false)

    override fun onResume() {
        super.onResume()
        Log.d(javaClass.simpleName, "onResume")
        mBannerVideoManager?.onResume()
    }

    override fun lazyLoad() {
//        mPresenter?.getPackage()
    }

    override fun showAd() {

    }

    override fun refreshDatas(platform: BackstagePlatform, goodListBean: GoodListBean?) {
        try{
            goodListBean?.let {
                loadGoods(it)
            }
        }catch (e: Exception){
            e.printStackTrace()
            logFile("刷新套餐数据异常-：${e.message}")
        }
    }

    override fun getPayCode(reqPayCodeBean: ReqPayCodeBean?) {
        reqPayCodeBean?.let { bean ->
            bean.reqData?.let { rd ->
                var title = ""
                var tips = ""
                var backscanTips = ""
                when (bean.goodBean.goodType){
                    PackageType.NORMAL -> {
                        title = "${BigDecimalUtil.getPrice(bean.goodBean.money)}${Config.CURRENCY_SYMBOLS}${bean.goodBean.amount}${getString(R.string.bi)}"
                        tips = bean.payIconBean.payName.ifEmpty { getString(R.string.scan_wx_ali) }
                        backscanTips = getString(R.string.pay_code_wx_ali)
                    }
                    PackageType.RECHARGE -> {
                        //充值套餐只能微信扫码
                        title = "${BigDecimalUtil.getPrice(bean.goodBean.money)}${Config.CURRENCY_SYMBOLS}${bean.goodBean.amount}${getString(R.string.bi)}"
                        tips = getString(R.string.scan_wx)
                        backscanTips = getString(R.string.pay_code_wx_ali)
                    }
                    PackageType.CASH -> {

                    }
                }

                if (platform != BackstagePlatform.YCH_SDK) {
                    showPaymentDialog(title, tips, backscanTips, 90, bean.k, bean.payIconBean)
                }
                EventBus.getDefault().post(GetPayCodeEvent(bean))
            }
        }
    }

    override fun postResult(reqStartResultBean: ReqStartResultBean?) {
        reqStartResultBean?.let { bean ->
            bean.reqData?.let {
                EventBus.getDefault().post(PostResultEvent(bean))
            }
        }
    }

    override fun showCoinsInfo(k: String, coins: String, outOrSave: Boolean, finish: Boolean) {
        dismissDialog("CoinsInfoDialog")
        refreshCoinsData(coins, outOrSave, finish)
        EventBus.getDefault().post(OutCoinsEvent(k, coins.toLong()))
    }

    override fun postBackscanPay(reqBackscanPayBean: ReqBackscanPayBean?) {
        logFile("上报反扫数据：${GsonUtil.getInstance()?.toJson(reqBackscanPayBean)}")
        reqBackscanPayBean?.let { bean ->
            bean.reqData?.let {
                EventBus.getDefault().post(PostBackscanPayEvent(bean))
            }
        }
    }

    override fun showCashGoods(cashGoods: MutableList<CashGoodBean>?, lastCashOrder: OrderEntity?) {
        cashGoods?.let {
            //显示现金购币窗口
            showCashPayDialog(it, lastCashOrder)
        }
    }

    override fun saveMoneyFinish(uuid: String, totalMoney: Long, coins: Long) {
        if (cashPayDialog == null){
            cashPayOut(totalMoney.toString(), coins.toString())
        }else{
            cashPayDialog?.refreshCashData(totalMoney.toString(), coins.toString())
        }

    }

    override fun refreshRemainCoins(coins: String) {
        refreshCoins(coins)
    }

    override fun uploadCashData(repData: Any) {
        postCashData(repData)
    }

    override fun refreshPayCode(data: String) {
        if (paymentDialog != null) {
            paymentDialog?.refreshQrCode(data)
        }
        if (ychPayDialog != null) {
            logFile("qrCode=$data")
            ychPayDialog?.refreshQrCode(data)
        }

    }

    override fun saveCoinLogin(saveCoinLoginBean: SaveCoinLoginBean?) {
        logFile("login success")
        saveCoinLoginBean?.run {
            saveCoinDialog?.let {
                it.login(orderNumber, userId)
                saveCoin(orderNumber, userId, true)
            }
        }
    }

    override fun checkSaveCoinsResult(checkSaveCoinsResultBean: CheckSaveCoinsResultBean) {
        if (checkSaveCoinsResultBean.result){
            saveCoinDialog?.saveFinish()
            //上报存币数据
            checkSaveCoinsResultBean.repData?.let {
                EventBus.getDefault().post(RepSaveCoinDataEvent(it))
            }
        }else{
            saveCoinDialog?.dismissNow()
        }
    }

    override fun getWithdrawalCode(result: GetWithdrawalCodeResult) {
        if (result.canShow){
            showRechargeQrCode(result.code)
        }else{
            showRechargeQrCode("")
            EventBus.getDefault().post(GetWithdrawalCodeEvent(""))
        }
    }

    override fun getMultCouponChannel(result: MutableList<CouponInfoBean>) {
        if (result.isNotEmpty()){
            showMultCouponDialog(getString(R.string.coupon), getString(R.string.verification_tips), result)
        }
    }

    override fun repWiteOffData(result: RepWriteOffDataBean?) {
        result?.let {
            it.repData?.let { data ->
                EventBus.getDefault().post(PostWriteOffDataEvent(it.platform, data))
            }
        }
    }

    override fun placeCashOrder(money: String, coins: String, uuid: String) {
        EventBus.getDefault().post(PlaceCashOrderEvent(KkbBuyPackageBean(when (Config.PRODUCT_TYPE){
            ProductType.CURRENCY -> 2
            ProductType.BEAD -> 1
        }, uuid, money, coins.toInt(), 3, payMoneyCent = money)))
    }

    override fun placeLocalWithdrawalOrder(reqStartResultBean: ReqStartResultBean?) {
        reqStartResultBean?.let { bean ->
            bean.reqData?.let {
                EventBus.getDefault().post(PlaceLocalWithdrawalOrderEvent(bean))
            }
        }
    }

    override fun showLoading() {

    }

    override fun hideLoading() {

    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        Log.d(javaClass.simpleName, "onHiddenChanged=$hidden")
        if (hidden) {
            mBannerVideoManager?.onPause()
        } else {
            //小广告
            isShowSmallAd(smallAd)
            //logo
            isShowLogo(logoShow)
            //加载余币数据
            loadCoins(autoCoins)
        }
    }

    override fun onPause() {
        super.onPause()
        Log.d(javaClass.simpleName, "onPause")
        mBannerVideoManager?.onPause()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        Log.d(javaClass.simpleName, "onDestroyView")
        mBannerVideoManager?.onDetachedFromWindow()
    }

    private fun loadGoods(goodListBean: GoodListBean){
        try {
            val normalList = goodListBean.normalList

            if (normalPackageAdapter == null){
                val normalLayoutManager = GridLayoutManager(App.instance, 3)
                binding.rvPakageNormal.layoutManager = normalLayoutManager
                normalPackageAdapter = GoodAdapter(requireContext(), normalList)
                normalPackageAdapter?.setOnItemClickListener(object : GoodAdapter.OnItemClickListener {
                    override fun onClick(goodBean: GoodBean?) {
                        if (!getDeviceStatus()){
                            showToastMsg(getString(R.string.device_err_tips))
                            return
                        }
                        goodBean?.let {
                            if (platform == BackstagePlatform.WHM_MQTT_HEX){
                                val payTypeList = makePayTypeData()
//                                if (country == 1 && payTypeList.size == 1){
//                                    //国内并且支付方式只有一个，直接跳转显示二维码
//                                    val payTypeData = payTypeList[0]
//                                    mPresenter?.getPayCode(goodBean, payTypeData)
//                                }else{
//                                    showPayTypeDialog(
//                                        getString(R.string.select_pay_type),
//                                        getString(R.string.pay_type),
//                                        payTypeList,
//                                        it,
//                                        30
//                                    )
//                                }
                                if (country == 1){
                                    //国内设备，聚合码支付
                                    mPresenter?.getPayCode(goodBean, PayTypeData(0, "扫码支付"))
                                }else{
                                    showPayTypeDialog(
                                        getString(R.string.select_pay_type),
                                        getString(R.string.pay_type),
                                        payTypeList,
                                        it,
                                        30
                                    )
                                }
                            }else if (platform == BackstagePlatform.YCH_SDK){
                                mPresenter?.getPayCode(goodBean, null)
                                val payTypeList = makePayTypeDataYch()
                                showYchPayDialog(
                                    getString(R.string.ych_buy_title),
                                    getString(R.string.ych_buy_scan),
                                    payTypeList,
                                    it,
                                    30
                                )
                            }else if (platform == BackstagePlatform.KKB){
//                                mPresenter?.getPayCode(goodBean, null)
                                val payTypeList = makePayTypeDataKkb()
                                showKkbPayDialog(it.goodName, "付款码付款", payTypeList, it, 30)
                            }else {
                                mPresenter?.getPayCode(goodBean, null)
                            }
                        }
                    }
                })
                binding.rvPakageNormal.adapter = normalPackageAdapter
                binding.rvPakageNormal.isSaveEnabled = false

            }else{
                normalPackageAdapter?.setData(normalList)
            }

            val rechargeList = goodListBean.rechargeList
            binding.llRechargePackage.visibility = if (rechargeList.isNotEmpty()) View.VISIBLE else View.GONE
            if (rechargeList.isEmpty() && lyyboxOpen) {
                binding.llRechargePackage.visibility = View.VISIBLE
                binding.rvPakageRecharge.visibility = View.GONE
                binding.rlRechargeBtn.visibility = View.VISIBLE
                return
            }else if (rechargeList.isEmpty() && !lyyboxOpen){
                binding.llRechargePackage.visibility = View.GONE
                return
            }
            binding.llRechargePackage.visibility = View.VISIBLE
            binding.rvPakageRecharge.visibility = View.VISIBLE
            binding.rlRechargeBtn.visibility = View.GONE
            if (rechargePackageAdapter == null) {
                val rechargeLayoutManager = GridLayoutManager(App.instance, 3)
                binding.rvPakageRecharge.layoutManager = rechargeLayoutManager
                rechargePackageAdapter = GoodAdapter(requireContext(), rechargeList)
                rechargePackageAdapter?.setOnItemClickListener(object :
                    GoodAdapter.OnItemClickListener {
                    override fun onClick(goodBean: GoodBean?) {
                        if (!getDeviceStatus()){
                            showToastMsg(getString(R.string.device_err_tips))
                            return
                        }
                        goodBean?.let {
                            if (platform == BackstagePlatform.WHM_MQTT_HEX){
                                val payTypeData = PayTypeData(254, "")
                                mPresenter?.getPayCode(goodBean, payTypeData)
                            }else {
                                mPresenter?.getPayCode(goodBean, null)
                            }
                        }
                    }
                })
                binding.rvPakageRecharge.adapter = rechargePackageAdapter
                binding.rvPakageRecharge.isSaveEnabled = false
            } else {
                rechargePackageAdapter?.setData(rechargeList)
            }
        }catch (e: Exception){
            e.printStackTrace()
            logFile("加载套餐数据异常：${e.message}")
        }
    }

    /**
     * 设置LOGO
     * @param show 显示或者隐藏
     */
    private fun isShowLogo(show: Boolean) {
        try {
            if (show){
                binding.ivLogo.visibility = View.VISIBLE
                val logoPath = FileUtil.getMediaFile(Config.DEF_LOGO_PATH)?.run {
                    if (isEmpty()) {
//                        R.drawable.logo_ic
                        R.mipmap.ic_logo_default
                    } else {
                        for (i in indices){
                            val logoData = this[i].split(",")
                            if (logoData[1] == "1"){
                                return@run logoData[0]
                            }
                        }
//                        R.drawable.logo_ic
                        R.mipmap.ic_logo_default
                    }
                }?: R.mipmap.ic_logo_default//R.drawable.logo_ic
                logFile("logo路径：$logoPath")
                Glide.with(requireContext())
                    .load(logoPath)
                    .fitCenter()
                    .into(binding.ivLogo)
            }else{
                binding.ivLogo.visibility = View.GONE
            }
        }catch (e: Exception){
            e.printStackTrace()
            logFile("显示logo异常：${e.message}")
        }
    }

    /**
     * 设置小广告
     * @param show 显示或者隐藏
     */
    private fun isShowSmallAd(show: Boolean) {
//        binding.banner.visibility = if (show) View.VISIBLE else View.GONE
        if (show) {
            if (mAdapter != null && mBannerVideoManager != null) {
                mBannerVideoManager?.onResume()
            } else {
//                initAd()
            }
        } else {
            if (mAdapter != null && mBannerVideoManager != null) {
                binding.banner.stop()
                mAdapter = null
                mBannerVideoManager?.onDetachedFromWindow()
                mBannerVideoManager = null
            }
        }
    }

    private fun initAd() {
        try {
            val dataList2: MutableList<ResourceBean> = mutableListOf()

            FileUtil.getMediaFile(Config.DEF_MEDIA_PATH)?.run {
                if (isEmpty()) {
                    null
                } else {
                    val temp: MutableList<ResourceBean> = mutableListOf()
                    forEach { filePath ->
                        filePath.split(",").let {
                            temp.add(ResourceBean(it[1].toInt(), it[0]))
                        }
                    }
                    temp
                }
            }.run {
                if (!isNullOrEmpty()) {
                    dataList2.addAll(this)
                }
            }

            if (dataList2.isEmpty()){
//                dataList2.add(ResourceBean(1, "https://flutter.cn/assets/images/cn/flutter-icon.png"))
                dataList2.add(ResourceBean(2, "https://media.w3.org/2010/05/sintel/trailer.mp4"))
//                dataList2.add(
//                    ResourceBean(
//                        1,
//                        "https://model-player.oss-cn-beijing.aliyuncs.com/bg_banner_pink.png"
//                    )
//                )
//                dataList2.add(ResourceBean(1, R.mipmap.bg_ad_default))
            }

            mAdapter = MediaVideoBannerAdapter(dataList2, R.mipmap.bg_ad_default, canTouchWidget)

            binding.banner.visibility = View.VISIBLE
            binding.banner.setUserInputEnabled(canSrollBanner)//banner禁止滑动
            binding.banner.isAutoLoop(false)
            binding.banner.setAdapter(mAdapter)
                .setIndicator(CircleIndicator(context), canShowIndicater)//是否显示指示器
                .setIndicatorGravity(IndicatorConfig.Direction.CENTER)
            mBannerVideoManager = BannerVideoManager(binding.banner, mAdapter, dataList2)
            mBannerVideoManager?.run {
                setPageChangeMillis(imageShowTime)
                setVideoPlayLoadWait(videoLoadTime)
                startAlterChangeResource()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("初始化广告异常：${e.message}")
        }
    }

    private fun loadOptionItem() {
        try {
            val gridLayoutManager = GridLayoutManager(App.instance, 4)
//            val linearLayoutManager = LinearLayoutManager(App.instance, LinearLayoutManager.HORIZONTAL, false)
            binding.rvHomeBtn.layoutManager = gridLayoutManager
            val linearSnapHelper = LinearSnapHelper().apply {
                attachToRecyclerView(binding.rvHomeBtn)
            }
            val homeBtns = getHomeBtnData()
            if (homeBtns.isEmpty()) {
                logFile("按钮数据为空")
                return
            }
            homeBtnAdapter = HomeBtnAdapter(App.instance, homeBtns)
            homeBtnAdapter?.setOnItemClickListener(object : HomeBtnAdapter.OnItemClickListener{
                override fun onClick(homeBtnBean: HomeBtnBean) {
                    if (!homeBtnBean.enable){
                        showToastMsg(getString(R.string.temporarily_closed_tips))
                        return
                    }

                    if (!getDeviceStatus()){
                        showToastMsg(getString(R.string.device_err_tips))
                        return
                    }

                    //homeBtnNames索引值
                    when (val bt = homeBtnBean.type) {
                        HomeButtonType.WITHDRAWAL -> handleWithdrawal()
                        HomeButtonType.MOBILE_PAY -> handleMobilePay()
                        HomeButtonType.CASH -> handleCashPay()
                        HomeButtonType.COUPON -> handleCoupon()
                        HomeButtonType.MEITUAN_COUPON -> handleMeituan()
                        HomeButtonType.TIKTOK_COUPON -> handleTitok()
                        HomeButtonType.SAVE -> handleMemberSave()
                        else -> {
                            logFile("未开放按钮类型：$bt")
                        }
                    }
                }
            })
            binding.rvHomeBtn.adapter = homeBtnAdapter
        }catch (e: Exception){
            e.printStackTrace()
            logFile("加载底部选项异常：${e.message}")
        }
    }

    /**
     * 获取首页底部选项
     * @return
     */
    private fun getHomeBtnData(): MutableList<HomeBtnBean> {
        return try {
            val btnList: MutableList<HomeBtnBean> = mutableListOf()
            for (i in homeBtnNames.indices){
                if (homeBtnNames[i].show) {
                    btnList.add(HomeBtnBean(i, homeBtnNames[i].name, false, homeBtnNames[i].type))
                }
            }

            var homeBtnList = "1"
//        if (platform == Constant.PLATFORM_LYY_SDK || platform == Constant.PLATFORM_LYY_BOX) {
//            homeBtnList = "1, 2"
//        } else if (platform == Constant.PLATFORM_DEFAULT) {
//            homeBtnList = SPHelper.getHomeBtn()
//        }
            homeBtnList = when (platform) {
                BackstagePlatform.DEF_MQTT -> "0,1,2,3"
                BackstagePlatform.LYY_SDK -> "0,1"
                BackstagePlatform.LYY_BOX -> "0,1"
                BackstagePlatform.WHM_MQTT -> "0,1,2,5"
                BackstagePlatform.WHM_MQTT_HEX -> "0,1,2,5"
                BackstagePlatform.YCH_SDK -> "0,1,2,5"
                BackstagePlatform.KKB -> "0,1,2,5"
            }
            logFile("homeBtnList = $homeBtnList")
            if (homeBtnList.isEmpty()) {
                return btnList
            }
            if (homeBtnList.contains(",")) {
                val ids = homeBtnList.split(",".toRegex()).dropLastWhile { it.isEmpty() }
                    .toTypedArray()
                for (id in ids) {
                    val index = id.trim().toInt()
                    btnList.forEach { btnBean ->
                        if (btnBean.pageId == index){
                            btnBean.enable = true
                        }
                    }
                }
                return btnList
            }else{
                val index = homeBtnList.toInt()
                btnList.forEach { btnBean ->
                    if (btnBean.pageId == index){
                        btnBean.enable = true
                    }
                }
            }
            btnList
        }catch (e: Exception){
            e.printStackTrace()
            logFile("")
            val result: MutableList<HomeBtnBean> = mutableListOf()
            result
        }

    }

    /**
     * 会员提币
     */
    private fun handleWithdrawal() {
        if (platform == BackstagePlatform.KKB){
            showLocalWithdrawalDialog()
        }else {
            mPresenter?.getWithdrawalCode(platform)
        }
    }

    /**
     * 移动支付
     */
    private fun handleMobilePay() {
        // TODO
    }

    /**
     * 现金购币
     */
    private fun handleCashPay() {
        try {
            mPresenter?.getCashGoods(platform)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("处理现金购币")
        }
    }

    /**
     * 优惠券
     */
    private fun handleCoupon() {
        mPresenter?.getMultCouponChannel(platform)
    }

    /**
     * 美团
     */
    private fun handleMeituan() {
        showCouponDialog(getString(R.string.meituan_coupon), getString(R.string.verification_tips), -1)
    }

    /**
     * 抖音
     */
    private fun handleTitok() {
        showCouponDialog(getString(R.string.titok_coupon), getString(R.string.verification_tips), -1)
    }

    /**
     * 会员存币
     */
    private fun handleMemberSave() {
//        showSaveDialog()
        showSaveCoinQrCode()
    }

    /**
     * 显示后台登录窗口
     */
    private fun showKeyboardDialog() {
        try {
            keyboardDialog?.dismissAllowingStateLoss()

            keyboardDialog = KeyboardDialog(object : KeyboardDialog.KeyboardListener {
                override fun dismiss() {
                    keyboardDialog = null
                }

                override fun openBackstage() {
                    EventBus.getDefault().post(SwitchFragmentEvent(FragmentEnum.BACKSTAGE_MAIN))
                }

                override fun showTips(string: String) {
                    showToastMsg(string)
                }

            })
            keyboardDialog?.showNow(parentFragmentManager, "Keyboard")
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("显示后台登录窗口异常：${e.message}")
        }
    }

    /**
     * 显示提示信息
     * @param title 提示标题
     * @param info 提示信息
     */
    private fun showInfo(title: String, info: String){
        try {
            infoDialog?.dismissAllowingStateLoss()

            infoDialog = InfoDialog(title, info, 60, object : InfoDialog.InfoDialogListener{
                override fun dismiss() {
                    logFile("提示信息窗口关闭")
                    infoDialog = null
                }
            })
            infoDialog?.showNow(parentFragmentManager, "InfoDialog")
        }catch (e: Exception){
            e.printStackTrace()
            logFile("显示提示信息异常：${e.message}")
        }
    }

    /**
     * 显示会员提币二维码
     */
    private fun showRechargeQrCode(code: String){
        try {
            withdrawalDialog?.dismissAllowingStateLoss()

            val title = getString(when (Config.PRODUCT_TYPE){
                ProductType.CURRENCY -> R.string.member_withdrawal
                ProductType.BEAD -> R.string.member_withdrawal_bead
            })
            val tips = getString(R.string.scan_wx)
            withdrawalDialog = WithdrawalDialog(title, tips, code, 60, object : WithdrawalDialog.WithdrawalDialogListener{
                override fun dismiss() {
                    logFile("提币二维码窗口关闭")
                    withdrawalDialog = null
                }

                override fun back() {
                    logFile("提币二维码窗口点击返回")
                }
            })
            withdrawalDialog?.showNow(parentFragmentManager, "WithdrawalDialog")
        }catch (e: Exception){
            e.printStackTrace()
            logFile("显示会员充值二维码异常：${e.message}")
        }
    }

    /**
     * 本地提币dialog
     */
    private fun showLocalWithdrawalDialog(){
        try {
            localWithdrawalDialog?.dismissAllowingStateLoss()

            localWithdrawalDialog = LocalWithdrawalDialog(getString(when (Config.PRODUCT_TYPE){
                ProductType.CURRENCY -> R.string.member_withdrawal
                ProductType.BEAD -> R.string.member_withdrawal_bead
            }),
                getString(when (Config.PRODUCT_TYPE){
                    ProductType.CURRENCY -> R.string.scan_withdrawal_coin
                    ProductType.BEAD -> R.string.scan_withdrawal_bead
                }),
                60,
                makeLocalWithdrawalGood(),
                object : LocalWithdrawalDialog.WithdrawalListener {
                    override fun dismiss() {
                        logFile("本地提币二维码窗口关闭")
                        SoftInputUtil.hideSoftInput(binding.root)
                        localWithdrawalDialog = null
                        EventBus.getDefault().post(QueryLgLoginCancelEvent(""))
                    }

                    override fun finish(uid: String, withdrawalQuantity: Int) {
                        if (withdrawalQuantity == 0) return
                        mPresenter?.placeLocalWithdrawalOrder(platform, uid, withdrawalQuantity)
                    }

                    override fun out(uid: String, withdrawalQuantity: Int) {
                        if (withdrawalQuantity == 0) return
                        mPresenter?.localWithdrawalOut(platform, uid, withdrawalQuantity.toString())
                    }

//                    override fun back() {
//                        logFile("存币二维码窗口点击返回")
//                    }
//
//                    override fun saveCoins(orderNumber: String, userId: String, transId: String) {
//                        logFile("校验存币订单数据：orderNumber=$orderNumber userId=$userId transId=$transId")
//                        saveCoin(orderNumber, userId, false)
//                        mPresenter?.checkSaveCoins(orderNumber, userId, transId)
//                    }
                })
            localWithdrawalDialog?.showNow(parentFragmentManager, "LocalWithdrawalDialog")
//            if (loginCode.isEmpty()){
//                EventBus.getDefault().post(GetLoginCodeEvent())
//            }
            EventBus.getDefault().post(GetLoginCodeEvent())
        }catch (e: Exception){
            e.printStackTrace()
            logFile("显示本地提取dialog异常：${e.message}")
        }
    }

    /**
     * 显示会员存币二维码
     */
    private fun showSaveCoinQrCode(){
        try {
            saveCoinDialog?.dismissAllowingStateLoss()

            saveCoinDialog = SaveCoinDialog(getString(when (Config.PRODUCT_TYPE){
                ProductType.CURRENCY -> R.string.member_save_coins
                ProductType.BEAD -> R.string.member_save_bead
            }),
                getString(when (Config.PRODUCT_TYPE){
                    ProductType.CURRENCY -> R.string.scan_save_coin
                    ProductType.BEAD -> R.string.scan_save_bead
                }),
                "", 60, object : SaveCoinDialog.SaveCoinDialogListener{
                override fun dismiss() {
                    logFile("存币二维码窗口关闭")
                    saveCoinDialog = null
                    mPresenter?.setSaveStatus(platform, false)
                    EventBus.getDefault().post(QueryLgLoginCancelEvent(""))
                }

                override fun back() {
                    logFile("存币二维码窗口点击返回")
                }

                override fun saveCoins(orderNumber: String, userId: String, transId: String, coins: String) {
                    logFile("校验存币订单数据：orderNumber=$orderNumber userId=$userId transId=$transId conis=$coins")
                    saveCoin(orderNumber, userId, false)
                    mPresenter?.checkSaveCoins(orderNumber, userId, transId, coins)
                }
            })
            saveCoinDialog?.showNow(parentFragmentManager, "SaveCoinDialog")
            //更新处理线程的状态
            mPresenter?.setSaveStatus(platform, true)
//            if (loginCode.isEmpty()){
//                EventBus.getDefault().post(GetLoginCodeEvent())
//            }
            EventBus.getDefault().post(GetLoginCodeEvent())
        }catch (e: Exception){
            e.printStackTrace()
            logFile("显示会员存币二维码异常：${e.message}")
            mPresenter?.setSaveStatus(platform, false)
        }
    }

    /**
     * 显示支付信息窗口
     * @param title 标题
     * @param scanTips 二维码提示
     * @param backscanTips 反扫提示
     * @param timeout 超时时间
     * @param k 订单号 （lyy版本）
     * @param payIconBean 支付icon数据
     */
    private fun showPaymentDialog(title: String, scanTips: String, backscanTips: String, timeout: Int, k: String, payIconBean: PayIconBean){
        try {
            paymentDialog?.dismissAllowingStateLoss()

            paymentDialog = PaymentDialog(title, scanTips, backscanTips, timeout, k, payIconBean, object : PaymentDialog.PaymentDialogListener{
                override fun dismiss() {
                    logFile("支付窗口关闭")
                    paymentDialog = null
                    openScan(false, ScanType.UNDEFINE)
                }

                override fun back(k: String) {
                    logFile("支付窗口点击返回")
                    mPresenter?.setOrderTimeout(k)
                }
            })
            paymentDialog?.showNow(parentFragmentManager, "PaymentDialog")
            scanK = k
            openScan(true, ScanType.PAY)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("显示支付窗口异常：${e.message}")
        }
    }

    /**
     * 显示支付信息窗口
     * @param goodBean 套餐数据
     */
    private fun showPayTypeDialog(title: String, tips: String, payTypeList: MutableList<PayTypeData>, goodBean: GoodBean, timeout: Int){
        try {
            payTypeDialog?.dismissAllowingStateLoss()

            payTypeDialog = PayTypeDialog(title, tips, payTypeList, goodBean, timeout, object : PayTypeDialog.PayTypeDialogListener{
                override fun dismiss() {
                    logFile("支付方式窗口关闭")
                    payTypeDialog = null
                }

                override fun back() {

                }

                override fun selectPayType(payTypeData: PayTypeData, goodBean: GoodBean) {
                    logFile("选中支付方式：${GsonUtil.getInstance()?.toJson(payTypeData)}")
                    mPresenter?.getPayCode(goodBean, payTypeData)
                }
            })
            payTypeDialog?.showNow(parentFragmentManager, "PayTypeDialog")
        }catch (e: Exception){
            e.printStackTrace()
            logFile("显示支付方式窗口异常：${e.message}")
        }
    }

    /**
     * 显示支付信息窗口
     * @param goodBean 套餐数据
     */
    private fun showYchPayDialog(title: String, tips: String, payTypeList: MutableList<PayTypeDataYch>, goodBean: GoodBean, timeout: Int){
        try {
            ychPayDialog?.dismissAllowingStateLoss()

            ychPayDialog = YchPayDialog(title, tips, payTypeList, goodBean, timeout, object : YchPayDialog.PayTypeDialogListener{
                override fun dismiss(transId: String) {
                    logFile("YCH支付方式窗口关闭 transId=$transId")
                    ychPayDialog = null
                    openScan(false, ScanType.PAY)
                    EventBus.getDefault().post(QueryPlaceOrderCancelEvent(transId))
                }

                override fun back() {

                }

                override fun selectPayType(payTypeData: PayTypeDataYch, goodBean: GoodBean) {
                    logFile("选中YCH支付方式：${GsonUtil.getInstance()?.toJson(payTypeData)}")
                }
            })
            ychPayDialog?.showNow(parentFragmentManager, "YchPayDialog")
            openScan(true, ScanType.PAY)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("显示YCH支付方式窗口异常：${e.message}")
        }
    }

    /**
     * 显示支付信息窗口
     * @param goodBean 套餐数据
     */
    private fun showKkbPayDialog(title: String, tips: String, payTypeList: MutableList<PayTypeDataYch>, goodBean: GoodBean, timeout: Int){
        try {
            kkbPayDialog?.dismissAllowingStateLoss()

            kkbPayDialog = KkbPayDialog(title, tips, payTypeList, goodBean, timeout, object : KkbPayDialog.PayTypeDialogListener{
                override fun dismiss(transId: String) {
                    logFile("KKB支付方式窗口关闭 transId=$transId")
                    kkbPayDialog = null
                    openScan(false, ScanType.PAY)
                    EventBus.getDefault().post(QueryPlaceOrderCancelEvent(transId))
                }

                override fun back() {

                }

                override fun selectPayType(payTypeData: PayTypeDataYch, goodBean: GoodBean) {
                    logFile("选中KKB支付方式：${GsonUtil.getInstance()?.toJson(payTypeData)}")
                }
            })
            kkbPayDialog?.showNow(parentFragmentManager, "KkbPayDialog")
            openScan(true, ScanType.PAY)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("显示KKB支付方式窗口异常：${e.message}")
        }
    }

    /**
     * 显示支付信息窗口
     * @param goodBean 套餐数据
     */
    private fun showCashPayDialog(cashGoods: MutableList<CashGoodBean>, lastCashOrder: OrderEntity?){
        try {

            cashPayDialog?.dismissAllowingStateLoss()

            cashPayDialog = CashPayDialog(getString(when (Config.PRODUCT_TYPE){
                ProductType.CURRENCY -> R.string.cash_pay
                ProductType.BEAD -> R.string.cash_pay_bead
            }), 60, cashGoods, lastCashOrder, object : CashPayDialog.CashPayListener{
                override fun dismiss() {
                    cashPayDialog = null
                }

                override fun finish(money: String, coins: String) {
                    cashPayOut(money, coins)
                }
            })
            cashPayDialog?.showNow(parentFragmentManager, "CashPayDialog")
            openInMoney(true)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("显示支付窗口异常：${e.message}")
            openInMoney(false)
        }
    }

    /**
     * 优惠券核销
     * @param title 标题
     * @param tips 提示语
     * @param couponType 核销方式
     */
    private fun showCouponDialog(title: String, tips: String, couponType: Int){
        try {

            couponDialog?.dismissAllowingStateLoss()

            couponDialog = CouponDialog(title, tips, couponType, 60, false, object : CouponDialog.CouponDialogListener{
                override fun dismiss() {
                    openScan(false, ScanType.COUPON)
                    couponDialog = null
                }

                override fun back() {

                }

                override fun verification(type: Int, couponData: String) {
                    mPresenter?.postBackscanData(type, couponData)
                }
            })
            couponDialog?.showNow(parentFragmentManager, "CouponDialog")
            openScan(true, ScanType.COUPON)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("显示优惠券核销窗口异常：${e.message}")
            openScan(false, ScanType.COUPON)
        }
    }

    /**
     * 优惠券核销
     * @param title 标题
     * @param tips 提示语
     * @param couponType 核销方式
     */
    private fun showMultCouponDialog(title: String, tips: String, couponInfoBeanList: MutableList<CouponInfoBean>){
        try {
            multCouponDialog?.dismissAllowingStateLoss()

            multCouponDialog = MultCouponDialog(title, tips, "", couponInfoBeanList, 60, object : MultCouponDialog.MultCouponDialogListener{
                override fun dismiss(transId: String) {
                    openScan(false, ScanType.COUPON)
                    multCouponDialog = null
                }

                override fun back() {

                }

            })
            multCouponDialog?.showNow(parentFragmentManager, "MultCouponDialog")
            openScan(true, ScanType.COUPON)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("显示优惠券核销窗口异常：${e.message}")
            openScan(false, ScanType.COUPON)
        }
    }

    /**
     * 现金购币，出币
     * @param money 金额
     * @param coins 出币数
     */
    private fun cashPayOut(money: String, coins: String){
        openInMoney(false)
        mPresenter?.cashPayOut(platform, money, coins)
    }

    /**
     * 优惠券核销
     * @param type 核销方式
     * @param data 核销数据
     */
    private fun couponVerification(type: Int, data: String){
        EventBus.getDefault().post(CouponVerificationEvent(type, data))
    }

    /**
     * 刷新出币或存币数据
     * @param coins 币数
     * @param outOrSave true-出币 false-存币
     * @param finish 是否结束
     */
    private fun refreshCoinsData(coins: String, outOrSave: Boolean, finish: Boolean, success: Boolean = true){
        try {
            if (outOrSave){
                if (coinsInfoDialog == null){
                    coinsInfoDialog = CoinsInfoDialog(getString(R.string.device_out_coins), getString(R.string.device_outing), coins, 20, object :CoinsInfoDialog.OutInfoDialogListener{
                        override fun dismiss() {
                            coinsInfoDialog = null
                        }

                        override fun back() {

                        }
                    })
                    coinsInfoDialog?.showNow(parentFragmentManager, "CoinsInfoDialog")
                }
                coinsInfoDialog?.refreshInfo(coins, finish, success)
            }else{
                saveCoinDialog?.let {
                    it.refreshSaveCoins(coins)
                    mPresenter?.refreshSaveCoins(it.getOrderNumber(), coins)
                }
            }
        }catch (e: Exception){
            e.printStackTrace()
            logFile("刷新出币或存币数据异常：${e.message}")
        }
    }

    private fun dismissDialog(dialogTag: String?){
        couponDialog?.run {
            if (tag != dialogTag){
                dismissAllowingStateLoss()
            }
        }

        multCouponDialog?.run {
            if (tag != dialogTag){
                dismissAllowingStateLoss()
            }
        }

        payTypeDialog?.run {
            if (tag != dialogTag){
                dismissAllowingStateLoss()
            }
        }

        paymentDialog?.run {
            if (tag != dialogTag){
                dismissAllowingStateLoss()
            }
        }

        coinsInfoDialog?.run {
            if (tag != dialogTag){
                dismissAllowingStateLoss()
            }
        }

        cashPayDialog?.run {
            if (tag != dialogTag){
                dismissAllowingStateLoss()
            }
        }

        withdrawalDialog?.run {
            if (tag != dialogTag){
                dismissAllowingStateLoss()
            }
        }

        saveCoinDialog?.run {
            if (tag != dialogTag){
                dismissAllowingStateLoss()
            }
        }

        infoDialog?.run {
            if (tag != dialogTag){
                dismissAllowingStateLoss()
            }
        }

        keyboardDialog?.run {
            if (tag != dialogTag){
                dismissAllowingStateLoss()
            }
        }

        ychPayDialog?.run {
            if (tag != dialogTag){
                dismissAllowingStateLoss()
            }
        }

        kkbPayDialog?.run {
            if (tag != dialogTag){
                dismissAllowingStateLoss()
            }
        }

        localWithdrawalDialog?.run {
            if (tag != dialogTag){
                dismissAllowingStateLoss()
            }
        }

        coinsInfoDialog?.run {
            if (tag == dialogTag){
                dismissAllowingStateLoss()
            }
        }
    }

    /**
     * 打开纸钞机
     * @param open
     */
    private fun openInMoney(open: Boolean){
        EventBus.getDefault().post(BanknoteEvent(open))
    }

    private fun makePayTypeData(): MutableList<PayTypeData>{
        if (payTypeStr.isBlank()){
            return mutableListOf()
        }
        val payTypeList = payTypeStr.split(";")
        if (payTypeList.isEmpty()){
            return mutableListOf()
        }
        val result: MutableList<PayTypeData> = mutableListOf()
        payTypeList.forEach { item ->
            if (item.isEmpty()){
                return@forEach
            }
            try {
                val itemSplit = item.split(",")
                result.add(PayTypeData(itemSplit[0].toInt(), itemSplit[1]))
            }catch (e: Exception){
                e.printStackTrace()
                logFile("支付方式数据解析异常：${e.message}")
            }
        }
        return result
    }

    private fun makePayTypeDataYch(): MutableList<PayTypeDataYch>{
//        val payTypeStr = "0,WeChat;1,Alipay"
//        val payTypeList = payTypeStr.split(";")
//        if (payTypeList.isEmpty()){
//            return mutableListOf()
//        }
        val result: MutableList<PayTypeDataYch> = mutableListOf()
//        payTypeList.forEach { item ->
//            if (item.isEmpty()){
//                return@forEach
//            }
//            try {
//                val itemSplit = item.split(",")
//                result.add(PayTypeDataYch(itemSplit[0].toInt(), itemSplit[1]))
//            }catch (e: Exception){
//                e.printStackTrace()
//                logFile("支付方式数据解析异常：${e.message}")
//            }
//        }
        result.add(PayTypeDataYch(0, "WeChatCodePay", "微信付款码", "", true))
        result.add(PayTypeDataYch(1, "AlipayCodePay", "支付宝付款码", "", false))
        return result
    }

    private fun makePayTypeDataKkb(): MutableList<PayTypeDataYch>{
        val result: MutableList<PayTypeDataYch> = mutableListOf()
        result.add(PayTypeDataYch(0, "WeChatCodePay", "微信付款码", "", true))
        result.add(PayTypeDataYch(1, "AlipayCodePay", "支付宝付款码", "", false))
        return result
    }

    private fun makeLocalWithdrawalGood(): MutableList<WithdrawalGoodBean>{
        return mutableListOf(
            WithdrawalGoodBean("", "", 1),
            WithdrawalGoodBean("", "", 5),
            WithdrawalGoodBean("", "", 10),
            WithdrawalGoodBean("", "", 20),
            WithdrawalGoodBean("", "", 50),
            WithdrawalGoodBean("", "", 100),
        )
    }

    /**
     * 打开或关闭反扫
     * @param open true-打开 false-关闭
     * @param type 反扫数据处理类型
     */
    private fun openScan(open: Boolean, type: ScanType){
        scanType = type
        EventBus.getDefault().post(ScanEvent(open))
    }

    /**
     * 存币开关
     */
    private fun saveCoin(orderNumber: String, userId: String, open: Boolean){
        EventBus.getDefault().post(SaveCoinEvent(orderNumber, userId, open))
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun regEvent(event: DevRegisterEvent) {
        try {
            Config.REG_EVENT = 1
            logFile("设备注册事件：${GsonUtil.getInstance()?.toJson(event)}")
//            if (event.show) {
//                binding.rlGood.visibility = View.GONE
//                binding.rlRegist.visibility = View.VISIBLE
//
//                Glide.with(binding.rlRegist)
//                    .load(QRCodeUtil.createQRCode(event.regCode, 500, 500))
//                    .fitCenter()
//                    .into(binding.ivRegistCode)
//
//                binding.tvRegTips.text = event.tips
//            } else {
//                binding.rlRegist.visibility = View.GONE
//                binding.rlGood.visibility = View.VISIBLE
//            }

            val regDataList = event.regDataList
            if (regDataList.isEmpty()){
                //没有注册码，所有设备注册完成
                binding.rlRegist.visibility = View.GONE
                binding.rlGood.visibility = View.VISIBLE
            }else{
                binding.rlGood.visibility = View.GONE
                binding.rlRegist.visibility = View.VISIBLE

                if (regCodeAdapter == null) {
                    binding.rvRegcode.layoutManager = if (regDataList.size == 1) {
                        LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
                    } else {
                        GridLayoutManager(context, 2)
                    }
                    regCodeAdapter = RegCodeAdapter(App.instance, regDataList)
                    binding.rvRegcode.adapter = regCodeAdapter
                }else{
                    binding.rvRegcode.layoutManager = if (regDataList.size == 1) {
                        LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
                    } else {
                        GridLayoutManager(context, 2)
                    }
                    regCodeAdapter?.setData(regDataList)
                }
            }

        } catch (e: Exception) {
            e.printStackTrace()
            logFile("设备注册事件异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refreshSignalEvent(event: RefreshSignalEvent) {
        try {
            logFile("刷新网络信号事件：${event.signal}")
            when (event.type) {
                "WIFI" -> {
                    binding.signalWifi.setWifi_state(event.signal)
                    binding.signal.visibility = View.GONE
                    binding.signalWifi.visibility = View.VISIBLE
                }

                else -> {
                    binding.signal.setSignalLevel(if (event.isConnected) event.signal else 0)
                    binding.signal.visibility = View.VISIBLE
                    binding.signalWifi.visibility = View.GONE
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("刷新网络信号事件异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refreshDeviceNumberEvent(event: RefreshDeviceNumberEvent) {
        try {
            logFile("显示设备编号事件：${event.dn}")
            event.dn?.let {
                devNumber = it
            }
            binding.tvDeviceNumber.text = event.dn
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("显示设备编号事件异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun showPayQrCodeEvent(event: ShowPayQrCodeEvent) {
        try {
            logFile("显示支付二维码事件")
            when (event.platform){
                BackstagePlatform.LYY_BOX -> {
                    lyyboxQrCode = event.codeData
                }
                else -> {
                    mPresenter?.refreshPayCode(event.codeData)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("显示支付二维码事件异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refreshGoodEvent(event: RefreshGoodsEvent) {
        try {
            logFile("刷新商品数据事件")

            mPresenter?.saveGoods(event.platform, event.dataList)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("刷新商品数据事件异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveOrderEvent(event: ReceiveOrderEvent) {
        try {
            logFile("订单支付成功事件")
            mPresenter?.recieveOrder(event.platform, null, event.orderData)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("订单支付成功事件异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveWithdrawalOrderEvent(event: ReceiveWithdrawalOrderEvent) {
        try {
            logFile("提币订单 事件")
            mPresenter?.recieveWithdrawalOrder(event.platform, event.orderData)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("提币订单 事件异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveOrderYchHttpEvent(event: ReceiveOrderYchHttpEvent) {
        try {
            logFile("YCH HTTP 订单处理事件")
            mPresenter?.recieveOrder(event.platform, null, event.orderDataYch)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("YCH HTTP 订单处理事件异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveOrderKkbHttpEvent(event: ReceiveOrderKkbHttpEvent) {
        try {
            logFile("KKB HTTP 订单处理事件")
            mPresenter?.recieveOrder(event.platform, null, event.orderDataKkb)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("KKB HTTP 订单处理事件异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refreshCoinsEvent(event: RefreshCoinsEvent) {
        try {
            logFile("刷新出币数据事件：${GsonUtil.getInstance()?.toJson(event)}")
            if (event.finish && event.outOrSave){
                mPresenter?.outCoins(event.coins.toLong())
            }
            refreshCoinsData(event.remainCoins, event.outOrSave, event.finish, event.success)
            mPresenter?.coinResponse(event.finish, event.success, event.coins)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("刷新商品数据事件异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receivedScanDataEvent(event: ReceivedScanDataEvent) {
        try {
            logFile("反扫数据处理事件：${GsonUtil.getInstance()?.toJson(event)}")
            if (paymentDialog != null){
                mPresenter?.postBackscanData(1, event.data)
            }
            couponDialog?.setCode(event.data)
            ychPayDialog?.let {
                val payType = it.getPayType()
                val goodBean = it.getSelectedGood()
                mPresenter?.postBackscanData(-1, event.data, goodBean, payType)
            }
            multCouponDialog?.let {
                it.setPayStatus(0)
                val channel = it.getChannel()
                if (channel.isNotEmpty()){
                    mPresenter?.repWiteOffData(platform, channel, event.data)
                }else{

                }
            }
            kkbPayDialog?.let {
                val payType = it.getPayType()
                val goodBean = it.getSelectedGood()
                mPresenter?.postBackscanData(-1, event.data, goodBean, payType)
            }

        } catch (e: Exception) {
            e.printStackTrace()
            logFile("反扫数据处理事件异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refreshCashDataEvent(event: RefreshCashDataEvent) {
        try {
            logFile("纸钞数据处理事件：${GsonUtil.getInstance()?.toJson(event)}")
            mPresenter?.saveMoney(event.checkMoney, event.totalMonty)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("纸钞数据处理事件异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun showCodeEvent(event: ShowCodeEvent) {
        try {
            logFile("二维码显示事件：${GsonUtil.getInstance()?.toJson(event)}")
            event.run {
                when (type){
                    0 -> {
                        if (code.contains(",")){
                            val qrCode = code.split(",")[0]
                            val transId = code.split(",")[1]
                            saveCoinDialog?.refreshQrCode(qrCode, transId)
                            localWithdrawalDialog?.refreshQrCode(qrCode)
                        }else {
                            saveCoinDialog?.refreshQrCode(code, "")
                            localWithdrawalDialog?.refreshQrCode(code)
                        }
                    }
                    1 -> {
                        withdrawalDialog?.refreshQrCode(code)
                    }
                    2 -> {
                        withdrawalDialog?.refreshQrCode(code)
                    }
                    else ->{

                    }
                }
            }

        } catch (e: Exception) {
            e.printStackTrace()
            logFile("显示二维码事件异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun userLoginEvent(event: UserLoginEvent) {
        try {
            logFile("用户登录WHM事件：${GsonUtil.getInstance()?.toJson(event)}")
            event.run {
                saveCoinDialog?.let {
                    mPresenter?.insertSaveCoin(userInfo)
                }
                withdrawalDialog?.run {

                }
            }

        } catch (e: Exception) {
            e.printStackTrace()
            logFile("用户登录WHM事件异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun userLoginYchEvent(event: UserLoginYchEvent) {
        try {
            logFile("用户登录YCH事件：${GsonUtil.getInstance()?.toJson(event)}")
            event.run {
                saveCoinDialog?.let {
                    mPresenter?.insertSaveCoin(userInfo)
                }
                withdrawalDialog?.run {

                }
            }

        } catch (e: Exception) {
            e.printStackTrace()
            logFile("用户登录YCH事件异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun userLoginKkbEvent(event: UserLoginKkbEvent) {
        try {
            logFile("用户登录KKB事件：${GsonUtil.getInstance()?.toJson(event)}")
            event.run {
                saveCoinDialog?.let {
                    mPresenter?.insertSaveCoin(userInfo)
                }
                localWithdrawalDialog?.loginSuccess(userInfo.displayId, userInfo.balanceCoin, userInfo.balancePearl)
            }

        } catch (e: Exception) {
            e.printStackTrace()
            logFile("用户登录KKB事件异常：${e.message}")
        }
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    fun placeOrderEvent(event: PlaceOrderEvent) {
        try {
            logFile("YCH HTTP 下单完成事件：${GsonUtil.getInstance()?.toJson(event)}")
            ychPayDialog?.setPayStatus(event.status)

            kkbPayDialog?.setPayStatus(event.orderId, event.status)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("YCH HTTP 下单完成事件异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveWriteOffOrderEvent(event: ReceiveWriteOffOrderEvent) {
        try {
            logFile("YCH 核销出币事件：${GsonUtil.getInstance()?.toJson(event)}")
            mPresenter?.recieveWriteOffOrder(event.platform, event.orderData)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("YCH 核销出币事件异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun placeLocalWithdrawalOrderRespEvent(event: PlaceLocalWithdrawalOrderRespEvent) {
        try {
            logFile("KKB 本地提币下单响应事件：${GsonUtil.getInstance()?.toJson(event)}")

            event.run {
                localWithdrawalDialog?.placeOrder(success, errMsg, memberId, balance)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("KKB 本地提币下单响应事件异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun wirteOffResultEvent(event: WirteOffResultEvent) {
        try {
            logFile("核销响应事件：${GsonUtil.getInstance()?.toJson(event)}")

            event.run {
                multCouponDialog?.let{ dialog ->
                    when(platform){
                        BackstagePlatform.DEF_MQTT -> {}
                        BackstagePlatform.LYY_SDK -> {}
                        BackstagePlatform.LYY_BOX -> {}
                        BackstagePlatform.WHM_MQTT -> {}
                        BackstagePlatform.WHM_MQTT_HEX -> {
                            val resp = writeOffResult as WriteOffRespWhmMqttHexBean
                            if (resp.result){
                                dialog.setPayStatus(1)
                            }else{
                                dialog.setPayStatus(2, resp.errMsg)
                            }
                        }
                        BackstagePlatform.YCH_SDK -> {}
                        BackstagePlatform.KKB -> {}
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("核销响应事件异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    fun dispenserOrderEvent(event: DispenserOrderEvent) {
        try {
            logFile("投币器投币出货事件：${GsonUtil.getInstance()?.toJson(event)}")
            mPresenter?.dispenserOrder(platform, event.repCashDataBean)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("投币器投币出货事件异常：${e.message}")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun getDeviceIdleEvent(event: GetDeviceIdleEvent) {
        try {
            logFile("获取订单处理线程状态事件：${GsonUtil.getInstance()?.toJson(event)}")
            val result = mPresenter?.getHandling()?: false
            EventBus.getDefault().post(GetDeviceIdleRespEvent(result))
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("获取订单处理线程状态异常：${e.message}")
        }
    }

}